package com.dxysun.springboot.advice;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

//@Component
@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice
{
	private static final Log logger = LogFactory.getLog(MyResponseBodyAdvice.class);

	@Override
	public boolean supports(MethodParameter methodParameter, Class aClass)
	{
		logger.info("MyResponseBodyAdvice supports Class:" + aClass.getSimpleName());
		logger.info("MyResponseBodyAdvice supports MethodParameter:" + methodParameter.getParameterType());
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass,
			ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse)
	{
		logger.info("MyResponseBodyAdvice serverHttpRequest:" + serverHttpRequest);
		logger.info("MyResponseBodyAdvice serverHttpRequest isEncrypt:" + serverHttpRequest.getHeaders().get("isEncrypt"));
		logger.info("MyResponseBodyAdvice serverHttpRequest encryptData:" + serverHttpRequest.getHeaders().get("encryptData"));
		/*ObjectMapper mapper = new ObjectMapper();
		String json = null;
		try
		{
			json = mapper.writeValueAsString(o);
		}
		catch (JsonProcessingException e)
		{
			e.printStackTrace();
		}*/
		logger.info("MyResponseBodyAdvice beforeBodyWrite");
		JSONObject resultJson = new JSONObject();
		resultJson.put("code", "ok");
		resultJson.put("msg", "in ResponseBodyAdvice");
		resultJson.put("result", o);
		if( o instanceof String)
		{
			return resultJson.toJSONString();
		}
		else
		{
			return resultJson;
		}
	}
}
